<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义props
const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true
  },
  // 是否显示序号列
  showIndex: {
    type: Boolean,
    default: true
  },
  // 是否显示操作列
  showOperation: {
    type: Boolean,
    default: true
  },
  // 是否显示新增按钮
  showAdd: {
    type: Boolean,
    default: false
  },
  // 是否显示批量删除按钮
  showBatchDeleteButton: {
    type: Boolean,
    default: true
  },
  // 是否支持搜索
  searchable: {
    type: Boolean,
    default: true
  },
  // 搜索字段
  searchFields: {
    type: Array,
    default: () => []
  },
  // 表格高度
  height: {
    type: String,
    default: '100%'
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['add', 'edit', 'delete', 'batch-delete', 'view', 'refresh'])

// 搜索关键词
const searchKeyword = ref('')
// 选中的行
const selectedRows = ref([])
// 表格实例
const tableRef = ref(null)

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchKeyword.value || !props.searchable || props.searchFields.length === 0) {
    return props.data
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return props.data.filter(item => {
    return props.searchFields.some(field => {
      const value = item[field]
      return value && String(value).toLowerCase().includes(keyword)
    })
  })
})

// 处理新增
const handleAdd = () => {
  emit('add')
}

// 处理编辑
const handleEdit = (row) => {
  emit('edit', row)
}

// 处理查看
const handleView = (row) => {
  emit('view', row)
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('delete', row)
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('batch-delete', selectedRows.value)
    // 清空选择
    selectedRows.value = []
  }).catch(() => {})
}

// 处理刷新
const handleRefresh = () => {
  searchKeyword.value = ''
  selectedRows.value = []
  emit('refresh')
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 监听数据变化，清空选择
watch(() => props.data, () => {
  selectedRows.value = []
})
</script>

<template>
  <div class="data-table-container">
    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <div class="left-actions">
        <el-button v-if="showAdd" type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button v-if="showBatchDeleteButton && selectedRows.length > 0" type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <slot name="toolbar"></slot>
      </div>
      
      <div class="right-actions">
        <el-input
          v-if="searchable && searchFields.length > 0"
          v-model="searchKeyword"
          placeholder="请输入关键词搜索"
          clearable
          prefix-icon="Search"
          style="width: 250px"
        />
      </div>
    </div>
    
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      :data="filteredData"
      border
      stripe
      :height="height"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" align="center" />
      
      <!-- 序号列 -->
      <el-table-column v-if="showIndex" type="index" label="序号" width="80" align="center" />
      
      <!-- 动态列 -->
      <el-table-column
        v-for="(column, index) in columns"
        :key="index"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :align="column.align || 'left'"
        :sortable="column.sortable"
        :fixed="column.fixed"
      >
        <template #default="scope">
          <!-- 自定义插槽 -->
          <slot :name="column.prop" :row="scope.row">
            <!-- 格式化函数 -->
            <template v-if="column.formatter">
              {{ column.formatter(scope.row[column.prop], scope.row) }}
            </template>
            <!-- 默认显示 -->
            <template v-else>
              {{ scope.row[column.prop] }}
            </template>
          </slot>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column
        v-if="showOperation"
        label="操作"
        width="180"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">
            <el-icon><View /></el-icon> 查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
          <slot name="operation" :row="scope.row"></slot>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.data-table-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  gap: 10px;
}
</style> 